<?php


namespace addons\ymypaypal\controller;


use addons\ymypaypal\services\PayPalService;
use app\common\controller\Api;
use fast\Arr;
use think\Controller;
use think\Log;

class Payment extends Api
{

    protected $noNeedLogin = ['payPalNotify'];
    /**
     * @des PayPal-Checkout-Notify
     * @author Mars
     * @return string
     */
    public function test(){
        echo 1;
    }
    public function payPalNotify( )
    {
        $request = $this->request;
        // 这里记录下日志, 本地测试回调时会用到
        $config = get_addon_config('ymypaypal');
        Log::info(var_export($request->header(), true));
        Log::info('PayPal----getContent-------'.($request->getContent()));
        $PayPalService = new PayPalService();
        $response = $PayPalService->verify($request,$config['checkout_notify_web_hook_id']);
        // 验证失败
        if (!$response) {
            return 'fail';
        }
        // 回调包的请求体
        $data = json_decode($response->request_body, true);

        $eventType = Arr::get($data, 'event_type');
        $resourceState = Arr::get($data, 'resource.state');
        // 验证回调事件类型和状态
        if ($eventType == 'PAYMENT.SALE.COMPLETED' && strcasecmp($resourceState, 'completed') == 0) {
            $paymentId = Arr::get($data, 'resource.parent_payment');
            if (!$paymentId) {
                return 'fail';
            }
            // 订单
            Log::write('$paymentId:'.$paymentId);


            // TODO: 这里写具体的支付完成后的流程(如: 更新订单的付款时间、状态 & 增加商品销量 & 发送邮件业务 等)
            $payment = $PayPalService->getPayment($paymentId);
            $transactions = $payment->getTransactions();
            foreach ($transactions as $transaction){
                $pay_no = $transaction->invoice_number;  //商家订单id
                $pay = model('app\api\model\wanlshop\Pay')
                    ->where(['pay_no' => $pay_no])
                    ->select();
                if(!$pay){
                    return ['code' => 10001 ,'msg' => '网络异常'];
                }
                // 支付类型
                $pay_type = 8;
                $user_id = 0;
                $order_list = [];
                $order_no = [];
                $pay_list = [];
                // 总价格
                $price = 0;
                foreach($pay as $row){
                    $price += $row['price'];
                    // 订单集
                    $order_no[] = $row['order_no'];
                    $user_id = $row['user_id'];
                }
                // -----------------------------支付成功，修改订单-----------------------------
                foreach($pay as $row){
                    // 新增付款人数&新增销量
                    foreach(model('app\api\model\wanlshop\OrderGoods')->where('order_id',$row['order_id'])->select() as $goods){
                        model('app\api\model\wanlshop\Goods')->where('id', $goods['goods_id'])->inc('payment')->inc('sales', $goods['number'])->update();
                    }
                    // 订单列表
                    $order_list[] = ['id' => $row['order_id'], 'state'  => 2, 'paymenttime' => time()];
                    // 支付列表
                    $pay_list[] = [
                        'id' => $row['id'],
                        'trade_no'  => $paymentId, // 第三方交易号
                        'pay_type'  => 'paypal', // 支付类型:0=余额支付,1=微信支付,2=支付宝支付
                        'pay_state'  => 1, // 支付状态 (支付回调):0=未支付,1=已支付,2=已退款
                        'total_amount' => $price, // 总金额
                        'actual_payment' => $row['price'], // 实际支付
                        'notice'  => json_encode($transaction)
                    ];
                }
                // 更新支付列表
                model('app\api\model\wanlshop\Pay')->saveAll($pay_list);
                // 更新订单列表
                model('app\api\model\wanlshop\Order')->saveAll($order_list);
                // 支付日志
                model('app\common\model\MoneyLog')->create([
                    'user_id' => $user_id,
                    'money' => -$price, // 操作金额
                    'memo' => 'Paypal支付订单', // 备注
                    'type' => 'pay', // 类型
                    'service_ids' => implode(",",$order_no) // 业务ID
                ]);
            }
            return 'success';
        }
        return 'fail';
    }

}